﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;
using System.Xml;

namespace DBConfigure
{
    public partial class frmDBConfigure : Form
    {
        private const string configFilePath = "database.config";

        private const string strDefaultServerIP = "127.0.0.1";
        private const string strDefaultDBName = "DB_RMS";
        private const string strDefaultUsername = "sa";
        private const string strDefaultPassword = "";

        public frmDBConfigure()
        {
            InitializeComponent();
        }

        // 加载数据库配置信息，并读取至界面内
        private void frmDBConfigure_Load(object sender, EventArgs e)
        {
            loadXMLConfigFileString();
        }

        // 以界面输入内容进行测试
        private void btn_testDB_Click(object sender, EventArgs e)
        {
            SqlConnection conn = null;
            SqlDataReader sdr = null;
            try
            {
                conn = new SqlConnection();
                conn.ConnectionString = String.Format("uid={2}; pwd={3}; Initial Catalog={1}; Data Source={0}",
                                        this.txt_serverip.Text.Trim(),
                                        this.txt_dbname.Text.Trim(),
                                        this.txt_username.Text.Trim(),
                                        this.txt_password.Text.Trim());
                conn.Open();
                // Create a sql command object.
                string strSql = "select count(staffID) from tb_staff;";
                SqlCommand command = new SqlCommand(strSql, conn);
                sdr = command.ExecuteReader(CommandBehavior.CloseConnection);
                if (sdr.Read() && Int32.Parse(sdr[0].ToString()) > 0)
                {
                    MessageBox.Show("配置数据库信息成功",
                                    "信息",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("配置数据库信息成功，无法连接到数据库",
                                    "信息",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Information);
                }
            }
            catch
            {
                MessageBox.Show("连接数据库失败，请稍候再试！",
                                        "错误",
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
            }
            finally
            {
                if (sdr != null) { sdr.Close(); sdr.Dispose(); sdr = null; }
                if (conn != null) { conn.Close(); conn.Dispose(); conn = null; }
            }
        }

        // 保存输入内容至数据库配置文件
        private void btn_OK_Click(object sender, EventArgs e)
        {
            createXMLFile(this.txt_serverip.Text.Trim(),
                                this.txt_dbname.Text.Trim(),
                                this.txt_username.Text.Trim(),
                                this.txt_password.Text.Trim());
            MessageBox.Show("保存设置成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }


        // 取消操作
        private void btn_cancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void createXMLFile(string strServerIP, string strDBName, string strUsername, string strPassword)
        {
            // 创建一个写入XML数据的文件流
            FileStream xmlFileStream = new FileStream(configFilePath, FileMode.Create);
            // 使用文件流对象创建一个XmlTextWriter对象
            XmlTextWriter myXmlWriter = new XmlTextWriter(xmlFileStream, Encoding.Unicode);
            // 指定文件输出的格式
            myXmlWriter.Formatting = System.Xml.Formatting.Indented;
            try
            {
                /**/
                ///  使用WriteXMLbyXmlWriter方法把数据写入XmlTextWriter对象中
                WriteXMLbyXmlWriter(myXmlWriter, strServerIP, strDBName, strUsername, strPassword);
                myXmlWriter.Close();
            }
            catch
            {
                throw new Exception("保存数据库配置文件失败!");
            }
            xmlFileStream.Close();
        }

        private void WriteXMLbyXmlWriter(XmlTextWriter writer, string serverip, string dbname, string username, string password)
        {
            writer.WriteStartElement("DatabaseConfig");
            writer.WriteElementString("ServerIP", serverip);
            writer.WriteElementString("DBName", dbname);
            writer.WriteElementString("LoginUser", username);
            writer.WriteElementString("Password", password);
            writer.WriteEndElement();
        }

        private void loadXMLConfigFileString()
        {
            if (!System.IO.File.Exists(configFilePath))
            {
                createXMLFile(strDefaultServerIP, strDefaultDBName, strDefaultUsername, strDefaultPassword);
            }
            FileStream xmlFileStream = new FileStream(configFilePath, FileMode.Open);
            XmlTextReader reader = new XmlTextReader(xmlFileStream);
            this.txt_serverip.Text = ReadXMLbyXMLReader(reader, "ServerIP");
            this.txt_dbname.Text = ReadXMLbyXMLReader(reader, "DBName");
            this.txt_username.Text = ReadXMLbyXMLReader(reader, "LoginUser");
            this.txt_password.Text = ReadXMLbyXMLReader(reader, "Password");
            reader.Close();
            xmlFileStream.Close();
        }

        private string ReadXMLbyXMLReader(System.Xml.XmlTextReader reader, string key)
        {
            while (reader.Read())
            {
                if (reader.Name == key)
                {
                    break;
                }
            }
            if (reader.Name == key && reader.Read() && reader.NodeType == XmlNodeType.Text)
                return reader.Value;
            else
                return "";
        }
    } // end of class
}
